package com.sgcc.pda.mdrh.h5.jsbridge;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.cepri.service.yingxiao.DtsManager;
import com.cepri.service.yingxiao.baidutts.BaiduTtsManager;
import com.cepri.service.yingxiao.baidutts.ITtsManager;
import com.sgcc.pda.baselibrary.utils.ToastUtils;
import com.sgcc.pda.common.aidl.CommonCallback;
import com.sgcc.pda.common.aidl.CommonParams;
import com.sgcc.pda.common.aidl.CommonResults;
import com.sgcc.pda.data.binder.DataBinderUtil;
import com.sgcc.pda.hw.binder.HardwareBinderUtil;
import com.sgcc.pda.hw.binder.IDEVBaseBinderUtil;
import com.sgcc.pda.hw.binder.ScannerBinderUtil;
import com.sgcc.pda.hzaidl.AIDLServiceImpl;
import com.sgcc.pda.hzaidl.IHZAidlCallback;
import com.sgcc.pda.mdrh.app.ZoomApplication;
import com.sgcc.pda.mdrh.h5.library.BridgeWebView;
import com.sgcc.pda.mdrh.h5.library.CallBackFunction;
import com.sgcc.pda.mdrh.h5.provider.DataProviderUtil;
import com.sgcc.pda.mdrh.h5.task.DBH5Task;
import com.sgcc.pda.mdrh.task.safelibrary.BuildConfig;
import com.sgcc.pda.mdrh.utils.AppManagerUtil;
import com.sgcc.pda.sdk.utils.FileUtils;
import com.sgcc.pda.sdk.utils.ZoomSPUtils;
import com.sgcc.pda.sdk.utils.db.SharepreferenceUtil;
import com.sgcc.pda.web.binder.WebBinderUtil;

import java.util.HashMap;
import java.util.Map;

public class MixRegisterHandler {

    private static final String TAG = "MixRegisterHandler";
    public static final int REQUEST_CODE_CHOOSE = 23;
    private CallBackFunction getPhotoFunction;

    public CallBackFunction getGetPhotoFunction() {
        return getPhotoFunction;
    }

    /**
     * 使用单例
     */
    private MixRegisterHandler() {
    }

    private static class SingletonHolder {
        private static final MixRegisterHandler INSTANCE = new MixRegisterHandler();
    }

    public static MixRegisterHandler getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 声明注册方案submitFromWeb
     *
     * @param webView
     */
    public void submitFromWeb(BridgeWebView webView) {
        registerIDEVBaseJS(webView);
        registerDataJS(webView);
        registerDBJS(webView);
        registerHardwareJS(webView);
        registerScannerJS(webView);
        registerWebJS(webView);
        //注册H5访问统一路由接口的入口
//        registerHZAidlimpl(webView);
        registerJumpActivity(webView);
        registerJumpPFaceActivity(webView);
    }

    private void registerHZAidlimpl(BridgeWebView bridgeWebView) {
        bridgeWebView.registerHandler("jsToJava_HZAidl", new Html5HandlerImpl() {
            @Override
            public void mixHandler(String data, final CallBackFunction function) {

                AIDLServiceImpl.getInstance().post(data, new IHZAidlCallback.Stub() {
                    @Override
                    public void callback(String s) {
                        function.onCallBack(s);
                    }
                });

            }
        });
    }

    /**
     * 注册掌机基础服务接口给H5调用
     *
     * @param bridgeWebView
     */
    private void registerIDEVBaseJS(final BridgeWebView bridgeWebView) {
        //初始化语音合成
        ITtsManager ttsManager;
        //初始化语音合成
        if (BuildConfig.USE_BAIDU_TTS) {
            ttsManager = BaiduTtsManager.getInstance();
        }else {
            ttsManager = DtsManager.getInstance();
        }
        ttsManager.init(bridgeWebView.getContext());
        bridgeWebView.registerHandler("jsToJava_IDEVBase", new MixBridgeHandlerImpl() {
            @Override
            public void mixHandler(final String originalData, CommonParams commonParams, final CallBackFunction function) {
                commonParams.addParam("activity", bridgeWebView.getContext());
                getPhotoFunction = function;
                IDEVBaseBinderUtil.getInstance().execute(commonParams, new CommonCallback() {
                    @Override
                    public void callback(final CommonResults commonResults) {
                        Log.d("h5调用", commonResults.toJSON());
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                //获取照片方法返回的结果是在MixWebViewActivity中onActivityResult中
                                if (!originalData.equals("takePhoto")) {
                                    function.onCallBack(commonResults.toJSON());
                                }
                            }
                        });
                    }
                });
            }
        });
    }

    /**
     * 注册数据服务接口给H5调用
     *
     * @param bridgeWebView
     */
    private void registerDataJS(BridgeWebView bridgeWebView) {
        bridgeWebView.registerHandler("jsToJava_Data", new MixBridgeHandlerImpl() {
            @Override
            public void mixHandler(String originalData, CommonParams commonParams, final CallBackFunction function) {
                DataBinderUtil.getInstance().execute(commonParams, new CommonCallback() {
                    @Override
                    public void callback(final CommonResults commonResults) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                function.onCallBack(commonResults.toJSON());
                            }
                        });
                    }
                });
            }
        });
    }

    /**
     * 注册数据库服务接口给H5调用
     *
     * @param bridgeWebView
     */
    private void registerDBJS(final BridgeWebView bridgeWebView) {
        bridgeWebView.registerHandler("jsToJava_DB", new MixBridgeHandlerImpl() {
            @Override
            public void mixHandler(String originalData, final CommonParams commonParams, final CallBackFunction function) {
                //开启异步任务
                DBH5Task dbh5Task = new DBH5Task(function);
                dbh5Task.execute(commonParams);
            }
        });
    }

    /**
     * 注册硬件基础服务接口给H5调用
     *
     * @param bridgeWebView
     */
    private void registerHardwareJS(BridgeWebView bridgeWebView) {
        bridgeWebView.registerHandler("jsToJava_Hardware", new MixBridgeHandlerImpl() {
            @Override
            public void mixHandler(String originalData, CommonParams commonParams, final CallBackFunction function) {
                HardwareBinderUtil.getInstance().execute(commonParams, new CommonCallback() {
                    @Override
                    public void callback(final CommonResults commonResults) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                function.onCallBack(commonResults.toJSON());
                            }
                        });
                    }
                });
            }
        });
    }

    /**
     * 注册扫描接口给H5调用
     *
     * @param bridgeWebView
     */
    private void registerScannerJS(BridgeWebView bridgeWebView) {
        bridgeWebView.registerHandler("jsToJava_Scanner", new MixBridgeHandlerImpl() {
            @Override
            public void mixHandler(String originalData, CommonParams commonParams, final CallBackFunction function) {
                ScannerBinderUtil.getInstance().execute(commonParams, new CommonCallback() {
                    @Override
                    public void callback(final CommonResults commonResults) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                function.onCallBack(commonResults.toJSON());
                            }
                        });
                    }
                });
            }
        });
    }

    /**
     * 注册上行通信接口给H5调用
     *
     * @param bridgeWebView
     */
    private void registerWebJS(BridgeWebView bridgeWebView) {
        //web通信，接口注册
        bridgeWebView.registerHandler("jsToJava_Web", new MixBridgeHandlerImpl() {
            @Override
            public void mixHandler(String originalData, final CommonParams commonParams, final CallBackFunction function) {
                WebBinderUtil.getInstance().execute(commonParams, new CommonCallback() {
                    @Override
                    public void callback(final CommonResults commonResults) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                function.onCallBack(commonResults.toJSON());
                            }
                        });
                    }
                });
            }
        });
    }

    /**
     * 注册ContentProvider给H5调用
     * (Sharepreference)
     *
     * @param bridgeWebView
     */
    private void registerProviderJS(BridgeWebView bridgeWebView) {
        //web通信，接口注册
        bridgeWebView.registerHandler("jsToJava_Provider", new MixBridgeHandlerImpl() {
            @Override
            public void mixHandler(String originalData, final CommonParams commonParams, final CallBackFunction function) {
                DataProviderUtil.getInstance().execute(commonParams, new CommonCallback() {
                    @Override
                    public void callback(CommonResults commonResults) {
                        function.onCallBack(commonResults.toJSON());
                    }
                });
            }
        });
    }

    /**
     * H5跳转app接口
     *
     * @param bridgeWebView
     */
    private void registerJumpActivity(final BridgeWebView bridgeWebView) {
        //web通信，接口注册
        bridgeWebView.registerHandler("jsToJava_Jump", new MixBridgeHandlerImpl() {
            @Override
            public void mixHandler(String originalData, final CommonParams commonParams, final CallBackFunction function) {
                Map<String, Object> params = commonParams.getParams();
                String packageName = (String) params.get("packageName");
                String startActivity = (String) params.get("startActivity");
                String tgId = (String) params.get("tgId");
                String stateDate = (String) params.get("stateDate");
                if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(startActivity)) {
                    try {
                        Intent intent = new Intent();
                        ComponentName componentName = new ComponentName(packageName, startActivity);
                        intent.setComponent(componentName);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("tgId", tgId);
                        intent.putExtra("stateDate", stateDate);
                        bridgeWebView.getContext().startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.show(bridgeWebView.getContext(), "应用打开失败");
                    }
                } else {
                    ToastUtils.show(bridgeWebView.getContext(), "包名或者启动类名为空");
                }
            }
        });
    }

    /**
     * H5跳转插件接口
     *
     * @param bridgeWebView.\
     */
    private CallBackFunction callBackFunction;
    //参数错误
    private static final String CODE_DEFAULT_ERROR = "-1";
    private static final String CODE_PARAMS_ERROR = "-2";
    private static final String CODE_FACE_NO_LICENSE = "-3";
    private static final String CODE_FACE_IMAGE_NOT_EXIST = "-4";
    private static final String CODE_FACE_NOT_INSTALLED = "-5";
    private static final String CODE_FACE_APP_OPEN_FAILURE = "-6";

    private void registerJumpPFaceActivity(BridgeWebView bridgeWebView) {
        //web通信，接口注册
        bridgeWebView.registerHandler("jsToJava_PluginJump", new MixBridgeHandlerImpl() {
            @Override
            public void mixHandler(String originalData, final CommonParams commonParams, final CallBackFunction function) {
                callBackFunction = function;
                Map<String, Object> params = commonParams.getParams();
                String packageName = (String) params.get("appPackageName");//
                String startActivity = (String) params.get("startActivity");
                String FLAG = (String) params.get("FLAG");
                String userCode = (String) params.get("userCode");
                String userName = (String) params.get("userName");
                String useFrontCamera = (String) params.get("useFrontCamera");
                if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(startActivity)) {
                    try {
                        // 应用是否安装
                        if (AppManagerUtil.getInstance().isAppInstalled(ZoomApplication.mTopActivity, packageName, "01")) {
                            if (TextUtils.equals(packageName, AppManagerUtil.FACE_APP_PACKAGE_NAME) && !FileUtils.licenseFileIsExists()) {
                                //如果是人脸识别app，并且license不存在
                                Intent intent = new Intent();
                                intent.putExtra("code", CODE_FACE_NO_LICENSE);
                                intent.putExtra("errorMessage", "未检测到人脸识别授权文件！");
                                faceFecognition(intent);
                                return;
                            }
                            //不传账号默认用当前登录人
                            if (TextUtils.isEmpty(userCode)) {
                                userCode = SharepreferenceUtil.getUserCode(ZoomApplication.mTopActivity);
                            }
                            //人脸搜索需要回调用户信息 单独处理，其他直接打开
                            if (TextUtils.isEmpty(userCode)) {
                                Intent intent = new Intent();
                                intent.putExtra("code", CODE_PARAMS_ERROR);
                                intent.putExtra("errorMessage", "人脸识别传入账号不能为空");
                                faceFecognition(intent);
                                return;
                            }
                            //判断需要检测的账号照片是否存在
                            if (!FileUtils.faceFileIsExists(userCode)) {
                                String msg = TextUtils.isEmpty(userName) ? userCode : userName;
                                Intent intent = new Intent();
                                intent.putExtra("code", CODE_FACE_IMAGE_NOT_EXIST);
                                intent.putExtra("errorMessage", msg + "的人脸照片不存在");
                                faceFecognition(intent);
                                return;
                            }
                            Intent intent = new Intent();
                            ComponentName componentName = new ComponentName(packageName, startActivity);
                            intent.setComponent(componentName);
                            intent.putExtra("FLAG", !TextUtils.isEmpty(FLAG) ? FLAG : "100");//"1",营销作业平台业务人脸识别,暂无其他业务，其它FLAG待定，不能为空
                            intent.putExtra("user_code", userCode);
                            intent.putExtra("useFrontCamera", useFrontCamera);
                            ZoomApplication.getInstance().getTopActivity().startActivityForResult(intent, 1234);
                        } else {
                            Intent intent = new Intent();
                            intent.putExtra("code", CODE_FACE_NOT_INSTALLED);
                            intent.putExtra("errorMessage", "人脸识别服务未安装！");
                            faceFecognition(intent);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Intent intent = new Intent();
                        intent.putExtra("code", CODE_FACE_APP_OPEN_FAILURE);
                        intent.putExtra("errorMessage", "人脸识别服务打开失败！");
                        faceFecognition(intent);
                    }
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("code", CODE_PARAMS_ERROR);
                    intent.putExtra("errorMessage", "app包名或者启动类名为空！");
                    faceFecognition(intent);
                }
            }
        });
    }

    public void faceFecognition(Intent data) {
        if (callBackFunction != null && data != null) {
            String errorMessage = data.getStringExtra("errorMessage");
            if (TextUtils.isEmpty(errorMessage)) {
                Map<String, Object> userInfoMap = new HashMap<>();
                userInfoMap.put("userCode", data.getStringExtra("userCode"));
                CommonResults commonResults = new CommonResults();
                commonResults.setCode("1");
                commonResults.setMsg("识别成功");
                commonResults.setResults(userInfoMap);
                callBackFunction.onCallBack(commonResults.toJSON());
            } else {
                //识别识别
                String code = data.getStringExtra("code");
                if (TextUtils.isEmpty(code)) {
                    code = CODE_DEFAULT_ERROR;
                }
                Map<String, Object> userInfoMap = new HashMap<>();
                userInfoMap.put("errorMessage", data.getStringExtra("errorMessage"));
                CommonResults commonResults = new CommonResults();
                commonResults.setCode(code);
                commonResults.setMsg(data.getStringExtra("errorMessage"));
                commonResults.setResults(userInfoMap);
                callBackFunction.onCallBack(commonResults.toJSON());
            }
        }
    }
}
